package com.zhenlong01.zhentest.controller;

import com.zhenlong01.zhentest.util.ImageUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author Administrator
 * @date 2019-08-28 22:09
 */
@RestController
public class ImageController {
    @GetMapping("/findimg")
    public void find_img(String fileName,HttpServletResponse response,@RequestParam(value="zoom",defaultValue="1") double zoom){
        boolean isWin = System.getProperty("os.name").indexOf("Windows")>=0;

        if(isWin){
            fileName = "d://upload/"+fileName;
        }else{
            fileName = "/upload/"+ fileName;
        }

        try {
            if(zoom<1){
                BufferedImage img =  ImageUtil.zoomPic(fileName,zoom);
                ImageIO.write(img,"jpg",response.getOutputStream());
                response.getOutputStream().close();
            }else {
                BufferedInputStream bis = new BufferedInputStream(
                        new FileInputStream(new File(fileName))
                );

                byte[] b = new byte[1024];
                int num;

                while ((num = bis.read(b)) != -1) {
                    response.getOutputStream().write(b, 0, num);
                }
                response.getOutputStream().flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
